package com.example.jpa1;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class AddPoemer extends Thread{
    int min;
    int max;
    List<String> urlList;

    PoemWjmRepository poemWjmRepository;

    public AddPoemer(List<String> urlList,
                     int min, int max
            , PoemWjmRepository poemWjmRepository){
        this.min = min;
        this.max = max;
        this.urlList = urlList;
        this.poemWjmRepository =
                poemWjmRepository;
    }

    @Override
    public void run() {
        super.run();
        for(int i=min;i<=max;i++){
            String html1 = null;
            try {
                html1 = AddPoem.getHTML(
                        "https://so.gushiwen.cn/"+
                                urlList.get(i));
                String reg = "<h1.*?>(.*?)</h1>";
                Pattern r2 = Pattern.compile(reg);
                Matcher m2 = r2.matcher(html1);
                String poemName="";
                if(m2.find()){
                    poemName = m2.group(1);
                }

                reg = "<h1.*?>(.*?)</h1>";
                r2 = Pattern.compile(reg);
                m2 = r2.matcher(html1);
                String poemChaodai="";
                if(m2.find()){
                    poemChaodai = m2.group(1);
                }

                reg = "<h1.*?>(.*?)</h1>";
                r2 = Pattern.compile(reg);
                m2 = r2.matcher(html1);
                String poetName="";
                if(m2.find()){
                    poetName = m2.group(1);
                }

                reg = "<h1.*?>(.*?)</h1>";
                r2 = Pattern.compile(reg);
                m2 = r2.matcher(html1);
                String poemType="";
                if(m2.find()){
                    poemType = m2.group(1);
                }

                reg = "<h1.*?>(.*?)</h1>";
                r2 = Pattern.compile(reg);
                m2 = r2.matcher(html1);
                String poemContent="";
                if(m2.find()){
                    poemContent = m2.group(1);
                }

                PoemWjm poem = new PoemWjm();
                poem.setPoemName(poemName);
                poem.setPoemChaodai(poemChaodai);
                poem.setPoetName(poetName);
                poem.setPoemType(poemType);
                poem.setPoemContent(poemContent);
                poemWjmRepository.save(poem);

                System.out.println(poem);
                Thread.sleep(2000+
                        (int)(Math.random()*3000));
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
